#!/usr/local/bin/node

const url = 'http://localhost:5984/',
db_name=process.argv[3],
codigo_postal=process.argv[2];
var rest=require('restler'),
i=0,
db = require('nano')(url).use(db_name);

if (process.argv.length < 4){
console.log('La sintaxis es: node cliente_BD.js <codigo postal> <nombre de la BD> <"all" si se quieren todos los paises, vacio en caso contrario>');
process.exit(1);
}

rest.get('http://api.geonames.org/postalCodeSearchJSON?postalcode=' + codigo_postal +'&maxRows=10&username=moxie').on('complete',function(data){
    var json=data.postalCodes;
    if (process.argv[4] != 'all'){
	while (i < json.length){
	    if (json[i].countryCode != 'ES') {json.splice(i,1);}
	    else {i++;}
	    }
    }
    console.log(json);
    i=0;
    while (i < json.length){
	db.insert( { i : json[i]},
		   function (error,http_body,http_headers) {
		       console.log(http_body);
		   });
	i++;
    }
});
